from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.keys import Keys


class BaseAction:

    # 初始化driver
    def __init__(self, driver):
        self.driver = driver
        # self.driver = webdriver.Remote()

    # 查找单个元素方法，传入元组（查找方式，值）
    def find_element(self, loc):
        self.driver.implicitly_wait(10)
        return self.driver.find_element(loc[0], loc[1])

    # 查找一组元素，传入元组（查找方式，值）
    def find_elements(self, loc):
        self.driver.implicitly_wait(10)
        return self.driver.find_elements(loc[0], loc[1])

    # 查找后然后点击元素，传入元组（查找方式，值）
    def click_element(self, loc):
        self.find_element(loc).click()

    # 直接点击元素
    def click_ele(self, ele):
        pass

    # 在查找到的输入框中输入值
    def input_keys(self, loc, word):
        self.find_element(loc).send_keys(word)

    # 清除输入框的内容
    def clear_words(self, loc):
        self.find_element(loc).clear()

    # 滑动窗口
    def swipe(self, x1, y1, x2, y2, duration=0):
        self.driver.swipe(x1, y1, x2, y2, duration)

    # 模拟手指轻敲元素或者位置
    def tab(self, ele=None, x=None, y=None):
        if ele is not None:
            TouchAction(self.driver).tap(ele).perform()
        else:
            TouchAction(self.driver).tap(x=x, y=y).perform()

    # 元素拖拽
    def drag_and_drop(self, loc1, loc2):
        self.driver.drag_and_drop(loc1, loc2)

    # 滑动窗口
    def move(self, loc=None, x1=None, y1=None, x2=None, y2=None, duration=2000):

        TouchAction(self.driver).long_press(el=loc, x=x1, y=y1, duration=duration).move_to(x=x2,
                                                                                           y=y2).release().perform()

    # 获取页面源码
    def get_page_source(self):
        return self.driver.page_source

    # 截图, 参数为绝对路径
    def screen_shot(self, filename):
        self.driver.get_screenshot_as_file(filename)

    # 键盘按键
    def press_key(self, key: int):
        self.driver.press_keycode(key)

    # 键盘按键2
    def key_event(self, key: int):
        self.driver.keyevent(key)

    # 下拉通知栏
    def pull_notification(self):
        self.driver.open_notifications()

    # 开启指定App, 仅限安卓
    def start_app(self, app_package, app_activity):
        self.driver.start_activity(app_package, app_activity)

    # 获取窗口尺寸，返回右下角坐标
    def get_window_size(self):
        s = self.driver.get_window_size()
        w, h = s['width'], s['height']
        return [w, h]
